import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'dart:math' as math;
import 'app_colors.dart';
import '../widgets/hand_drawn_icon.dart';
import '../widgets/hand_drawn_decoration.dart';

/// 应用主题
class AppTheme {
  static ThemeData get lightTheme {
    return ThemeData(
      useMaterial3: true,
      colorScheme: ColorScheme.light(
        primary: AppColors.primary,
        onPrimary: Colors.white,
        secondary: AppColors.secondary,
        onSecondary: Colors.white,
        tertiary: AppColors.tertiary,
        background: AppColors.background,
        surface: AppColors.cardBackground,
        error: AppColors.error,
      ),
      
      // 应用栏主题
      appBarTheme: AppBarTheme(
        backgroundColor: Colors.white,
        foregroundColor: AppColors.textPrimary,
        elevation: 0,
        centerTitle: false,
        titleTextStyle: TextStyle(
          fontSize: 18,
          fontWeight: FontWeight.w500,
          color: AppColors.textPrimary,
        ),
        iconTheme: IconThemeData(
          color: AppColors.textPrimary,
        ),
      ),
      
      // 卡片主题
      cardTheme: CardTheme(
        color: AppColors.cardBackground,
        shadowColor: Colors.black.withOpacity(0.1),
        elevation: 2,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        margin: EdgeInsets.symmetric(vertical: 8, horizontal: 0),
      ),
      
      // 悬浮按钮主题
      elevatedButtonTheme: ElevatedButtonThemeData(
        style: ElevatedButton.styleFrom(
          backgroundColor: AppColors.primary,
          foregroundColor: Colors.white,
          padding: EdgeInsets.symmetric(horizontal: 24, vertical: 12),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          elevation: 0,
          textStyle: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
      
      // 轮廓按钮主题
      outlinedButtonTheme: OutlinedButtonThemeData(
        style: OutlinedButton.styleFrom(
          foregroundColor: AppColors.primary,
          side: BorderSide(color: AppColors.primary, width: 1.5),
          padding: EdgeInsets.symmetric(horizontal: 24, vertical: 12),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          textStyle: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
      
      // 文本按钮主题
      textButtonTheme: TextButtonThemeData(
        style: TextButton.styleFrom(
          foregroundColor: AppColors.primary,
          padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          textStyle: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
      
      // 输入装饰主题
      inputDecorationTheme: InputDecorationTheme(
        filled: true,
        fillColor: Colors.white,
        contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 16),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(
            color: Colors.grey.shade300,
            width: 1,
          ),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(
            color: Colors.grey.shade300,
            width: 1,
          ),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(
            color: AppColors.primary,
            width: 1.5,
          ),
        ),
        errorBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide(
            color: AppColors.error,
            width: 1,
          ),
        ),
        hintStyle: TextStyle(
          fontSize: 16,
          color: Colors.grey.shade500,
        ),
      ),
      
      // 文本主题
      textTheme: TextTheme(
        displayLarge: TextStyle(
          fontSize: 28,
          fontWeight: FontWeight.bold,
          color: AppColors.textPrimary,
        ),
        displayMedium: TextStyle(
          fontSize: 24,
          fontWeight: FontWeight.bold,
          color: AppColors.textPrimary,
        ),
        displaySmall: TextStyle(
          fontSize: 22,
          fontWeight: FontWeight.bold,
          color: AppColors.textPrimary,
        ),
        headlineLarge: TextStyle(
          fontSize: 20,
          fontWeight: FontWeight.bold,
          color: AppColors.textPrimary,
        ),
        headlineMedium: TextStyle(
          fontSize: 18,
          fontWeight: FontWeight.bold,
          color: AppColors.textPrimary,
        ),
        headlineSmall: TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.bold,
          color: AppColors.textPrimary,
        ),
        titleLarge: TextStyle(
          fontSize: 18,
          fontWeight: FontWeight.w500,
          color: AppColors.textPrimary,
        ),
        titleMedium: TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.w500,
          color: AppColors.textPrimary,
        ),
        titleSmall: TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.w500,
          color: AppColors.textPrimary,
        ),
        bodyLarge: TextStyle(
          fontSize: 16,
          color: AppColors.textPrimary,
        ),
        bodyMedium: TextStyle(
          fontSize: 14,
          color: AppColors.textPrimary,
        ),
        bodySmall: TextStyle(
          fontSize: 12,
          color: AppColors.textSecondary,
        ),
        labelLarge: TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.w500,
          color: AppColors.textPrimary,
        ),
        labelMedium: TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.w500,
          color: AppColors.textPrimary,
        ),
        labelSmall: TextStyle(
          fontSize: 10,
          fontWeight: FontWeight.w500,
          color: AppColors.textSecondary,
        ),
      ),
      
      // 底部导航栏主题
      bottomNavigationBarTheme: BottomNavigationBarThemeData(
        backgroundColor: Colors.white,
        selectedItemColor: AppColors.primary,
        unselectedItemColor: AppColors.textSecondary,
        selectedLabelStyle: TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.w500,
        ),
        unselectedLabelStyle: TextStyle(
          fontSize: 12,
        ),
        type: BottomNavigationBarType.fixed,
        elevation: 8,
      ),
      
      // 标签栏主题
      tabBarTheme: TabBarTheme(
        labelColor: AppColors.primary,
        unselectedLabelColor: AppColors.textSecondary,
        indicatorColor: AppColors.primary,
        labelStyle: TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.w500,
        ),
        unselectedLabelStyle: TextStyle(
          fontSize: 14,
        ),
      ),
      
      // 芯片主题
      chipTheme: ChipThemeData(
        backgroundColor: AppColors.cardBackground,
        disabledColor: Colors.grey.shade300,
        selectedColor: AppColors.primary.withOpacity(0.2),
        secondarySelectedColor: AppColors.secondary.withOpacity(0.2),
        padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        labelStyle: TextStyle(
          fontSize: 14,
          color: AppColors.textPrimary,
        ),
        secondaryLabelStyle: TextStyle(
          fontSize: 14,
          color: AppColors.textPrimary,
        ),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
          side: BorderSide(
            color: Colors.grey.shade300,
            width: 1,
          ),
        ),
      ),
      
      // 分割线主题
      dividerTheme: DividerThemeData(
        color: Colors.grey.shade200,
        thickness: 1,
        space: 24,
      ),
      
      // 滑块主题
      sliderTheme: SliderThemeData(
        activeTrackColor: AppColors.primary,
        inactiveTrackColor: Colors.grey.shade300,
        thumbColor: AppColors.primary,
        overlayColor: AppColors.primary.withOpacity(0.2),
        trackHeight: 4,
      ),
      
      // 进度指示器主题
      progressIndicatorTheme: ProgressIndicatorThemeData(
        color: AppColors.primary,
        circularTrackColor: Colors.grey.shade200,
        linearTrackColor: Colors.grey.shade200,
      ),
      
      // 开关主题
      switchTheme: SwitchThemeData(
        thumbColor: MaterialStateProperty.resolveWith((states) {
          if (states.contains(MaterialState.selected)) {
            return AppColors.primary;
          }
          return Colors.grey.shade400;
        }),
        trackColor: MaterialStateProperty.resolveWith((states) {
          if (states.contains(MaterialState.selected)) {
            return AppColors.primary.withOpacity(0.5);
          }
          return Colors.grey.shade300;
        }),
      ),
      
      // 复选框主题
      checkboxTheme: CheckboxThemeData(
        fillColor: MaterialStateProperty.resolveWith((states) {
          if (states.contains(MaterialState.selected)) {
            return AppColors.primary;
          }
          return Colors.transparent;
        }),
        checkColor: MaterialStateProperty.all(Colors.white),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(4),
        ),
        side: BorderSide(
          color: Colors.grey.shade400,
          width: 1.5,
        ),
      ),
      
      // 单选按钮主题
      radioTheme: RadioThemeData(
        fillColor: MaterialStateProperty.resolveWith((states) {
          if (states.contains(MaterialState.selected)) {
            return AppColors.primary;
          }
          return Colors.grey.shade600;
        }),
      ),
      
      // 浮动操作按钮主题
      floatingActionButtonTheme: FloatingActionButtonThemeData(
        backgroundColor: AppColors.primary,
        foregroundColor: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
      ),
      
      // 对话框主题
      dialogTheme: DialogTheme(
        backgroundColor: AppColors.cardBackground,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        titleTextStyle: TextStyle(
          fontSize: 18,
          fontWeight: FontWeight.bold,
          color: AppColors.textPrimary,
        ),
        contentTextStyle: TextStyle(
          fontSize: 16,
          color: AppColors.textPrimary,
        ),
      ),
      
      // 提示框主题
      tooltipTheme: TooltipThemeData(
        decoration: BoxDecoration(
          color: AppColors.textPrimary.withOpacity(0.9),
          borderRadius: BorderRadius.circular(8),
        ),
        textStyle: TextStyle(
          fontSize: 14,
          color: Colors.white,
        ),
      ),
      
      // 底部模态框主题
      bottomSheetTheme: BottomSheetThemeData(
        backgroundColor: AppColors.cardBackground,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(24),
            topRight: Radius.circular(24),
          ),
        ),
      ),
      
      // 时间选择器主题
      timePickerTheme: TimePickerThemeData(
        backgroundColor: AppColors.cardBackground,
        hourMinuteTextStyle: TextStyle(
          fontSize: 24,
          fontWeight: FontWeight.bold,
          color: AppColors.textPrimary,
        ),
        dayPeriodTextStyle: TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.bold,
          color: AppColors.textPrimary,
        ),
        dialHandColor: AppColors.primary,
        dialBackgroundColor: Colors.grey.shade200,
        hourMinuteColor: AppColors.cardBackground,
        dayPeriodColor: AppColors.cardBackground,
        dayPeriodBorderSide: BorderSide(
          color: Colors.grey.shade300,
          width: 1,
        ),
      ),
      
      // 日期选择器主题
      datePickerTheme: DatePickerThemeData(
        backgroundColor: AppColors.cardBackground,
        headerBackgroundColor: AppColors.primary,
        headerForegroundColor: Colors.white,
        headerHeadlineStyle: TextStyle(
          fontSize: 20,
          fontWeight: FontWeight.bold,
          color: Colors.white,
        ),
        headerHelpStyle: TextStyle(
          fontSize: 14,
          color: Colors.white.withOpacity(0.8),
        ),
        dayStyle: TextStyle(
          fontSize: 14,
          color: AppColors.textPrimary,
        ),
        yearStyle: TextStyle(
          fontSize: 14,
          color: AppColors.textPrimary,
        ),
        weekdayStyle: TextStyle(
          fontSize: 12,
          color: AppColors.textSecondary,
        ),
        todayBorder: BorderSide(
          color: AppColors.primary,
          width: 1,
        ),
        dayBackgroundColor: MaterialStateProperty.resolveWith((states) {
          if (states.contains(MaterialState.selected)) {
            return AppColors.primary;
          }
          return Colors.transparent;
        }),
        dayForegroundColor: MaterialStateProperty.resolveWith((states) {
          if (states.contains(MaterialState.selected)) {
            return Colors.white;
          }
          return AppColors.textPrimary;
        }),
        yearBackgroundColor: MaterialStateProperty.resolveWith((states) {
          if (states.contains(MaterialState.selected)) {
            return AppColors.primary;
          }
          return Colors.transparent;
        }),
        yearForegroundColor: MaterialStateProperty.resolveWith((states) {
          if (states.contains(MaterialState.selected)) {
            return Colors.white;
          }
          return AppColors.textPrimary;
        }),
      ),
    );
  }
  
  /// 创建手绘风格的容器
  static Widget createHandDrawnContainer({
    required Widget child,
    Color color = Colors.white,
    double borderWidth = 2.0,
    Color borderColor = Colors.black,
    double borderRadius = 8.0,
    EdgeInsetsGeometry padding = const EdgeInsets.all(16.0),
  }) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 8),
      child: CustomPaint(
        painter: _HandDrawnContainerPainter(
          color: color,
          borderWidth: borderWidth,
          borderColor: borderColor,
          borderRadius: borderRadius,
        ),
        child: Padding(
          padding: padding,
          child: child,
        ),
      ),
    );
  }
}

/// 手绘风格的容器绘制器
class _HandDrawnContainerPainter extends CustomPainter {
  final Color color;
  final double borderWidth;
  final Color borderColor;
  final double borderRadius;
  
  _HandDrawnContainerPainter({
    required this.color,
    required this.borderWidth,
    required this.borderColor,
    required this.borderRadius,
  });
  
  @override
  void paint(Canvas canvas, Size size) {
    final rect = Rect.fromLTWH(0, 0, size.width, size.height);
    final rrect = RRect.fromRectAndRadius(
      rect,
      Radius.circular(borderRadius),
    );
    
    // 填充背景
    final fillPaint = Paint()
      ..color = color
      ..style = PaintingStyle.fill;
    canvas.drawRRect(rrect, fillPaint);
    
    // 绘制手绘风格的边框
    final borderPaint = Paint()
      ..color = borderColor
      ..style = PaintingStyle.stroke
      ..strokeWidth = borderWidth
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round
      ..isAntiAlias = true;
    
    // 添加一些随机性使边框看起来像手绘的
    final path = Path();
    final random = _PseudoRandom(size.width.toInt() * 1000 + size.height.toInt());
    
    // 左上角到右上角
    _addWobblyLine(path, borderRadius, 0, size.width - borderRadius, 0, random);
    
    // 右上角到右下角
    _addWobblyLine(path, size.width, borderRadius, size.width, size.height - borderRadius, random);
    
    // 右下角到左下角
    _addWobblyLine(path, size.width - borderRadius, size.height, borderRadius, size.height, random);
    
    // 左下角到左上角
    _addWobblyLine(path, 0, size.height - borderRadius, 0, borderRadius, random);
    
    // 绘制圆角
    _addWobblyArc(path, borderRadius, borderRadius, 180, 270, random); // 左上角
    _addWobblyArc(path, size.width - borderRadius, borderRadius, 270, 360, random); // 右上角
    _addWobblyArc(path, size.width - borderRadius, size.height - borderRadius, 0, 90, random); // 右下角
    _addWobblyArc(path, borderRadius, size.height - borderRadius, 90, 180, random); // 左下角
    
    canvas.drawPath(path, borderPaint);
  }
  
  // 添加波浪线
  void _addWobblyLine(Path path, double startX, double startY, double endX, double endY, _PseudoRandom random) {
    final dx = endX - startX;
    final dy = endY - startY;
    final distance = math.sqrt(dx * dx + dy * dy);
    final segments = (distance / 5).ceil();
    
    if (segments <= 1) {
      path.lineTo(endX, endY);
      return;
    }
    
    path.moveTo(startX, startY);
    
    for (int i = 1; i <= segments; i++) {
      final t = i / segments;
      final x = startX + dx * t;
      final y = startY + dy * t;
      
      // 添加一些随机偏移使线条看起来不规则
      final offset = random.nextDouble() * 2 - 1;
      final perpX = -dy / distance * offset;
      final perpY = dx / distance * offset;
      
      path.lineTo(x + perpX, y + perpY);
    }
  }
  
  // 添加波浪弧
  void _addWobblyArc(Path path, double centerX, double centerY, double startAngle, double endAngle, _PseudoRandom random) {
    final angleStep = 5;
    
    for (int angle = startAngle.toInt(); angle < endAngle.toInt(); angle += angleStep) {
      final radians = angle * 3.14159 / 180;
      final nextRadians = (angle + angleStep) * 3.14159 / 180;
      
      final x1 = centerX + borderRadius * math.cos(radians);
      final y1 = centerY + borderRadius * math.sin(radians);
      final x2 = centerX + borderRadius * math.cos(nextRadians);
      final y2 = centerY + borderRadius * math.sin(nextRadians);
      
      // 添加一些随机偏移
      final offset = random.nextDouble() * 1.5 - 0.75;
      final midX = (x1 + x2) / 2 + offset;
      final midY = (y1 + y2) / 2 + offset;
      
      path.moveTo(x1, y1);
      path.lineTo(midX, midY);
      path.lineTo(x2, y2);
    }
  }
  
  @override
  bool shouldRepaint(_HandDrawnContainerPainter oldDelegate) {
    return oldDelegate.color != color ||
        oldDelegate.borderWidth != borderWidth ||
        oldDelegate.borderColor != borderColor ||
        oldDelegate.borderRadius != borderRadius;
  }
}

/// 伪随机数生成器，用于生成一致的"随机"效果
class _PseudoRandom {
  int _seed;
  
  _PseudoRandom(this._seed);
  
  double nextDouble() {
    _seed = (_seed * 1103515245 + 12345) & 0x7FFFFFFF;
    return _seed / 0x7FFFFFFF;
  }
} 